package com._119yn.host.gst200.database.dao.impl;

import com._119yn.host.gst200.database.dao.DeviceStatusDao;
import com._119yn.host.gst200.database.entity.DeviceStatus;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class DeviceStatusDaoImpl implements DeviceStatusDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public long insert(DeviceStatus deviceStatus) {
        String sql = "insert into DEVICE_STATUS (DEVICE_ID, ALARM, FAULT, ACTION, STARTUP, SHIELD, LAST_UPDATE) values (?, ?, ?, ?, ?, ?, ?)";
        return jdbcTemplate.update(
                sql,
                deviceStatus.getDeviceId(),
                deviceStatus.getAlarm(),
                deviceStatus.getFault(),
                deviceStatus.getAction(),
                deviceStatus.getStartup(),
                deviceStatus.getShield(),
                deviceStatus.getLastUpdate()
        );
    }

    @Override
    public long deleteByDeviceId(String deviceId) {
        String sql = "DELETE FROM DEVICE_STATUS WHERE DEVICE_ID = ?";
        return jdbcTemplate.update(sql, deviceId);
    }

    @Override
    public long truncate() {
        String sql = "TRUNCATE TABLE DEVICE_STATUS";
        return jdbcTemplate.update(sql);
    }

    @Override
    public long updateByDeviceId(DeviceStatus deviceStatus) {
        String sql = "UPDATE DEVICE_STATUS SET ALARM = ?, FAULT = ?, ACTION = ?, STARTUP = ?, SHIELD = ?, LAST_UPDATE = ? WHERE DEVICE_ID = ?";
        return jdbcTemplate.update(
                sql,
                deviceStatus.getAlarm(),
                deviceStatus.getFault(),
                deviceStatus.getAction(),
                deviceStatus.getStartup(),
                deviceStatus.getShield(),
                deviceStatus.getLastUpdate(),
                deviceStatus.getDeviceId()
        );
    }

    @Override
    public DeviceStatus selectByDeviceId(String deviceId) {
        String sql = "SELECT * FROM DEVICE_STATUS WHERE DEVICE_ID = ?";
        List<DeviceStatus> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DeviceStatus.class), deviceId);
        if (list.isEmpty()) {
            return null;
        }
        return list.getFirst();
    }

    @Override
    public List<DeviceStatus> selectAll() {
        String sql = "SELECT * FROM DEVICE_STATUS";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(DeviceStatus.class));
    }

}
